package com.common.app.utls

import android.graphics.drawable.Drawable
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.common.app.data.bean.AdInfoBean
import com.common.app.data.repository.CommonPurposeApi
import com.common.base.app.extras.getContext
import com.common.base.data.CommonBean
import com.common.base.utils.SpUtilsManagement
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2024/6/17
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class AdInfoLoader private constructor(val type: AdInfoType) {

    companion object {
        private val instances = mutableMapOf<AdInfoType, AdInfoLoader>()

        fun getInstance(type: AdInfoType): AdInfoLoader {
            return instances.getOrPut(type) { AdInfoLoader(type) }
        }
    }

    sealed class AdInfoType(val type: Int, val path: String)

    object HomePopupAd : AdInfoType(1, "popup")
    object SplashAd : AdInfoType(2, "opening")
    //object HomeBanner : AdInfoType(3, "profile/banner")//合入首页页面接口
    object ClassifyBanner : AdInfoType(4, "category/banner")
    object MineBanner : AdInfoType(5, "profile/banner")//我的页面

    var scope = CoroutineScope(Dispatchers.IO)

    private val AD_INFO_KEY = "last_show_ad_" + type.path
    private val currentDay = SimpleDateFormat("yyyyMMdd", Locale.getDefault()).format(Date())
    private var lastShowId: String? = null
    private var hasShow: Boolean = false
    private var lastShowDay: String? = null
    private var resultData: AdInfoBean? = null
    private var isLoad: Boolean = false

    interface AdInfoCallback {
        fun onAdInfoLoaded(adInfoBean: AdInfoBean?)
        fun onError(e: Throwable)
    }

    init {
        val info = SpUtilsManagement.getString(AD_INFO_KEY).split("-")
        if (info.size > 1) {
            lastShowId = info[0]
            lastShowDay = info[1]
        }
    }

    fun recordAdShow() {
        val info = resultData ?: return
        lastShowDay = currentDay
        lastShowId = info.Id.toString()
        hasShow = true
        SpUtilsManagement.putString(AD_INFO_KEY, "${lastShowId}-${lastShowDay}")
    }

    fun getAdInfo(): AdInfoBean? {
        if (shouldShowAd()) {
            return resultData
        }
        return null
    }

    fun shouldShowAd(): Boolean {
        val info = resultData ?: return false
        if (!info.prepared) {
            return false
        }
        if (lastShowId != info.Id.toString()) {
            return true
        }
        if (info.AppShowTactics == 1) {
            if (lastShowDay == currentDay) {
                return false
            }
        } else if (info.AppShowTactics == 2) {
            if (hasShow) {
                return false
            }
        }
        return true
    }

    fun requestAd(callback: AdInfoCallback?) {
        if (isLoad) return
        scope.launch {
            isLoad = true
            RxHttp.get(CommonPurposeApi.USER_GET_SPLASH_PIC_LIST)
                .addPath("type", type.path)
                .toFlow<CommonBean<AdInfoBean>>()
                .catch { e ->
                    isLoad = false
                    callback?.onError(e)
                }.collect {
                    isLoad = false
                    if (it.isSuccess()) {
                        it.Data?.apply {
                            resultData=this
                            downloadPicture(this)
                            callback?.onAdInfoLoaded(this)
                        }

                    }
                }
        }
    }


    private fun downloadPicture(adInfoBean: AdInfoBean) {
        Glide.with(getContext()).load(adInfoBean.ImgUrl).listener(
            object : RequestListener<Drawable?> {
                override fun onLoadFailed(
                    e: GlideException?, model: Any?,
                    target: Target<Drawable?>, isFirstResource: Boolean
                ): Boolean {
                    adInfoBean.prepared = false
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable,
                    model: Any,
                    target: Target<Drawable?>?,
                    dataSource: DataSource,
                    isFirstResource: Boolean
                ): Boolean {
                    adInfoBean.prepared = true
                    return false
                }
            }).preload()
    }
}